package com.sinoatma.physignsmonitor.fragment


import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.bigkoo.pickerview.view.WheelTime.dateFormat
import com.common.frame.base.BaseFragment
import com.common.frame.extension.setSingleClick
import com.common.frame.utils.Utils.encodeAsBitmap
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IFillFormatter
import com.github.mikephil.charting.formatter.ValueFormatter
import com.hjq.toast.ToastUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.journeyapps.barcodescanner.CaptureActivity
import com.sinoatma.physignsmonitor.MyApp
import com.sinoatma.physignsmonitor.MyApp.Companion.excelService
import com.sinoatma.physignsmonitor.MyApp.Companion.stopMonitorFlag1
import com.sinoatma.physignsmonitor.R
import com.sinoatma.physignsmonitor.adapter.BpBleAdapter
import com.sinoatma.physignsmonitor.bean.*
import com.sinoatma.physignsmonitor.constant.*
import com.sinoatma.physignsmonitor.constant.Constant.BPStartCmd
import com.sinoatma.physignsmonitor.constant.Constant.tempStartCmd
import com.sinoatma.physignsmonitor.databinding.FragmentBloodTransBinding
import com.sinoatma.physignsmonitor.utils.FileUtils
import com.sinoatma.physignsmonitor.utils.FileUtils.isFirstLineEndsWith
import com.sinoatma.physignsmonitor.view.DialogUtil
import com.sinoatma.physignsmonitor.view.LoadProgressDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * 输血监控首页
 */
class BloodTransFragment : BaseFragment<BloodTransViewModel,FragmentBloodTransBinding>() {
    override fun layoutId(): Int =R.layout.fragment_blood_trans
    var handler = Handler()
    var maxVisibleDataPoints = 12
    lateinit var loadProgressDialog: LoadProgressDialog
    lateinit var dateFormat: SimpleDateFormat
    lateinit var adapter1: BpBleAdapter
    var lastAddDataTime: Long = 0 // 用于记录上次添加数据的时间戳，初始化为0
    var spoCount=0
    var temperatureConnectConnect=0


    var spo: Runnable = object : Runnable {
        override fun run() {
            LiveEventBus.get("receiveCmd1", SendCmd::class.java).post(SendCmd(1, Constant.sopQueryCmd))
            handler.postDelayed(this, 1000)
        }
    }
    var bp: Runnable = object : Runnable {
        override fun run() {
            LiveEventBus.get("receiveCmd2", SendCmd::class.java).post(SendCmd(1, Constant.BPTestCmd))
            handler.postDelayed(this, 10000)
        }
    }



    override fun initData() {
        loadProgressDialog = LoadProgressDialog(requireActivity())
    }

    override fun initView() {
        dateFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
        initChart1()
        initChart2()
        if (viewModel.headList.size==0){
            viewModel.initHeadExcel()
        }
        adapter1=BpBleAdapter(viewModel.bpList1)
        binding.layoutMonitorInterface1.bpRecycler.layoutManager= LinearLayoutManager(requireActivity())
        binding.layoutMonitorInterface1.bpRecycler.adapter=adapter1
        binding.layoutMonitorInterface2.tvEarlyWarningDate.text=viewModel.sdfDate.format(Date())
    }


    override fun initListener() {
        super.initListener()

        binding.layoutMonitorInterface1.tvScanCode.setSingleClick {
            viewModel.scanType=0
            startScan()
        }

        binding.layoutMonitorInterface1.personInfoLayout.setSingleClick {
            infoFillIn()
        }
        binding.tvMonitoringControl1.setSingleClick {
            if (binding.tvMonitoringControl1.text.toString()=="停止监测"){
                loadProgressDialog.showWithAutoClose("正在结束监测，数据整理中...",8)
                viewModel.excelListDataTemp.addAll(viewModel.excelListData)
                lifecycleScope.launch(Dispatchers.IO){
                    viewModel.excelListData.clear()
//                    Log.e("zsy","现在这里有几个数据${viewModel.excelListDataTemp.size}")
                     MyApp.excelService.bloodCollectExportExcel1(viewModel.excelListDataTemp, viewModel.headList, viewModel.filePath)
                    stopMonitorFlag1=1
                }
                if (ModeFlag==0){
                    loadProgressDialog.dismiss()
                    lifecycleScope.launch(Dispatchers.IO) {
                        Log.e("zsy","${viewModel.monitorCode1}")
                        viewModel.insertRecord(
                            MonitorRecordEntity(bloodDonationCode=viewModel.monitorCode1,
                                name=viewModel.monitorName1,sex=viewModel.monitorSex1,
                                warningTimes=viewModel.numberEarlyWarning1,dateStr=viewModel.sdfFile.format(Date()),
                                fileAddress=viewModel.filePath)
                        )
                        withContext(Dispatchers.Main){
                            stopMonitorFlag1=0
                            viewModel.filePath=""
                            viewModel.monitorCode1=""
                            viewModel.monitorName1=""
                            viewModel.monitorSex1=""
                            viewModel.monitorAge1=""
                            viewModel.numberEarlyWarning1=0
                            binding.layoutMonitorInterface1.scanCodeLayout.visibility= View.VISIBLE
                            binding.layoutMonitorInterface1.bloodDonationInfoLayout.visibility= View.GONE
                            binding.layoutMonitorInterface1.tvScanCodeNum.text=""
                            binding.layoutMonitorInterface1.tvPersonInfo.text="个人信息"
                            viewModel.bpList1.clear()
                            adapter1.notifyDataSetChanged()
                        }
                    }
                }
            }
            else
            {
                if (viewModel.monitorCode1.isEmpty()){
                    loadProgressDialog.showWithAutoClose("请先录入条码!",2)
                    return@setSingleClick
                }
                if (ModeFlag==1){
                    viewModel.uploadInfo()
                }
                if (viewModel.o2ringConnectStatus1==0){
                    loadProgressDialog.showWithAutoClose("血氧设备连接中...",20)
                    lifecycleScope.launch(Dispatchers.IO){
                        viewModel.initExcelFolder("${viewModel.monitorName1}","${viewModel.monitorCode1}")
                        Log.e("zsy","${viewModel.filePath}")
                    }
                    LiveEventBus.get("receiveCmd1",SendCmd::class.java).post(SendCmd(type = 3, cmd = O2RingMac))
                    if (TempMac.isNotEmpty()) {
                        LiveEventBus.get("receiveCmd3", SendCmd::class.java).postDelay(SendCmd(type = 3, cmd = TempMac), 3000)
                    }
                }else{
                    lifecycleScope.launch(Dispatchers.IO){
                        viewModel.initExcelFolder("${viewModel.monitorName1}","${viewModel.monitorCode1}")
                    }
                }
            }
        }

        binding.layoutMonitorInterface1.tvStartBp.setSingleClick {
            if (viewModel.monitorCode1.isEmpty()){
                loadProgressDialog.showWithAutoClose("请先录入条码!",2)
                return@setSingleClick
            }
            when (binding.layoutMonitorInterface1.tvStartBp.text) {
                "停止测量" -> {
                    LiveEventBus.get("receiveCmd2",SendCmd::class.java).postDelay(SendCmd(type = 1, cmd = Constant.BPStopCmd),500)
                    binding.layoutMonitorInterface1.tvStartBp.text="开始测量"
                }
                "开始测量" -> {
                    if (viewModel.bPConnectStatus1){
                        LiveEventBus.get("receiveCmd2",SendCmd::class.java).postDelay(SendCmd(type = 1, cmd = Constant.BPStartCmd),500)
                        binding.layoutMonitorInterface1.tvStartBp.text="停止测量"
                    }else{
                        loadProgressDialog.setMessage("血压设备连接中...")
                        LiveEventBus.get("receiveCmd2",SendCmd::class.java).post(SendCmd(type = 3, cmd = BPMac))
                    }
                }
            }
        }
    }


    override fun initObserve() {
        super.initObserve()
        LiveEventBus.get("upFile",Int::class.java).observe(this, androidx.lifecycle.Observer {
            if (it==1){
                stopMonitorFlag1=0
                val excelFile = File(viewModel.filePath)
                Log.e("zsy","数据已成功导出到Excel文件 ${excelFile.length()}")
                if (excelFile.exists()) {
                    Log.e("zsy","文件是否存在=${excelFile.exists()}")
                    viewModel.uploadFile(excelFile)
                }
                viewModel.excelListDataTemp.clear()
                binding.tvMonitoringControl1.text.toString()=="开始监测"
            }
        })


        LiveEventBus.get("DataNotify", MsgBleData::class.java).observe(this, androidx.lifecycle.Observer {
            when(it.type){
                1->{// 左侧血压计数据
                    if (it.bleData!!.contains("aa55430701")){
                        val sdf = SimpleDateFormat("HH:mm:ss")
                        val currentDate = Date()
                        val timeStr = sdf.format(currentDate)
                        val currentTimeMillis = currentDate.time
                        // 计算当前时间与上次添加数据时间的时间差（单位：秒）
                        val timeDiff = TimeUnit.MILLISECONDS.toSeconds(currentTimeMillis - lastAddDataTime)

                        if (timeDiff >= 2) {
                            var bpStatus = "0"
                            bpStatus = if (it.bleData!!.substring(16, 18).toInt(16) in 60..89 && it.bleData!!.substring(12, 14).toInt(16) in 90..139) {
                                "0"
                            } else {
                                if (it.bleData!!.substring(12, 14).toInt(16).toInt() > 139 || it.bleData!!.substring(12, 14).toInt(16).toInt() > 89) {
                                    "1"
                                } else {
                                    "2"
                                }
                            }
                            viewModel.bpData1="${it.bleData!!.substring(12, 14).toInt(16)}/${it.bleData!!.substring(16, 18).toInt(16)}"
                            viewModel.bpList1.add(BpDataBean(time = timeStr, h_pressure = "${it.bleData!!.substring(12, 14).toInt(16)}", l_pressure = "${it.bleData!!.substring(16, 18).toInt(16)}", bloodPressureStatus = bpStatus))
                            adapter1.notifyDataSetChanged()
                            // 更新上次添加数据的时间为当前时间
                            lastAddDataTime = currentTimeMillis
                            binding.layoutMonitorInterface1.tvStartBp.text="开始测量"
                        }
                    }
                }
                2->{// 左侧 血氧 计数据
                    if (it.bleData!!.length>=4){
                        if (spoCount>15 && !viewModel.tempConnectStatus1){
                            if (temperatureConnectConnect==0){
                                LiveEventBus.get("receiveCmd3",SendCmd::class.java).post(SendCmd(type = 3, cmd = TempMac))
                            }
                            temperatureConnectConnect++
                        }

                        addData2(it.bleData!!.subSequence(0,2).toString().toInt(16), it.bleData!!.subSequence(2,4).toString().toInt(16))
                        if (viewModel.monitorCode1.isNotEmpty() && viewModel.filePath.isNotEmpty() && stopMonitorFlag1==0){
                            binding.tvMonitoringControl1.text="停止监测"
                            var pr=it.bleData!!.subSequence(2,4).toString().toInt(16)
                            var spo=it.bleData!!.subSequence(0,2).toString().toInt(16)
                            if (spo in 80..93 && pr!=0){
                                viewModel.alertStatusRecordSpo1="血氧偏低"
                                viewModel.alertStatusValueSpo1="10"
                            }else{
                                viewModel.alertStatusRecordSpo1=""
                                viewModel.alertStatusValueSpo1=""
                            }
                            if (pr !in 60..100 && pr!=0){
                                if (pr<60){
                                    viewModel.alertStatusRecordPr1="脉搏偏低"
                                    viewModel.alertStatusValuePr1="20"
                                }else{
                                    viewModel.alertStatusRecordPr1="脉搏偏高"
                                    viewModel.alertStatusValuePr1="20"
                                }
                            }else{
                                viewModel.alertStatusRecordPr1=""
                                viewModel.alertStatusValuePr1=""
                            }

                            if (viewModel.bpData1.isNotEmpty()){
                                val bpSplit = viewModel.bpData1.split("/")
                                if (bpSplit[1].toInt() > 89 || bpSplit[0].toInt() > 139) {
                                    viewModel.alertStatusRecordBp1="血压偏高"
                                    viewModel.alertStatusValueBp1="30"
                                } else  if (bpSplit[1].toInt() < 60 || bpSplit[0].toInt() < 90){
                                    viewModel.alertStatusRecordBp1="血压偏低"
                                    viewModel.alertStatusValueBp1="30"
                                }
                            }else{
                                viewModel.alertStatusRecordBp1=""
                                viewModel.alertStatusValueBp1=""
                            }
                            var earlyWarningTime=""
                            if (viewModel.alertStatusRecordSpo1.isNotEmpty() || viewModel.alertStatusRecordPr1.isNotEmpty() || viewModel.alertStatusRecordBp1.isNotEmpty()){
                                earlyWarningTime=viewModel.sdfEarlyWarning.format(Date())
                                viewModel.numberEarlyWarning1+=1
                            }
                            if (viewModel.temperature.isNotEmpty()) {
                                if (viewModel.temperature.toFloat() !in 35.5..37.3) {
                                    viewModel.alertStatusRecordTemp1 = "体温异常"
                                    viewModel.alertStatusValueTemp1="40"
                                }
                            }else{
                                viewModel.alertStatusRecordTemp1=""
                                viewModel.alertStatusValueTemp1=""
                            }

                            if (earlyWarningTime.isNotEmpty()  && (binding.layoutMonitorInterface2.tvEarlyWarningRecord.text.toString().isEmpty() ||    FileUtils.isFirstLineEndsWith(alarmRecord1,"结束"))){
                                Log.e("zsy","异常信息开始")
                                alarmRecord1="${viewModel.monitorCode1}:异常状态:${viewModel.alertStatusRecordSpo1}${viewModel.alertStatusRecordPr1}${viewModel.alertStatusRecordBp1}${viewModel.alertStatusRecordTemp1}:${viewModel.sdfWarning.format(Date())}:开始\n${alarmRecord1}"
                                binding.layoutMonitorInterface2.tvEarlyWarningRecord.text="${alarmRecord1}"
                                viewModel.exception("${viewModel.alertStatusValueSpo1}|${viewModel.alertStatusValuePr1}|${viewModel.alertStatusValueBp1}|${viewModel.alertStatusValueTemp1}",
                                "10",
                                    "${viewModel.alertStatusRecordSpo1}|${viewModel.alertStatusRecordPr1}|${viewModel.alertStatusRecordBp1}|${viewModel.alertStatusRecordTemp1}",
                                "${spo}|${pr}|${viewModel.bpData1}|${viewModel.temperature}")
                            }else if (viewModel.alertStatusRecordSpo1.isEmpty() && viewModel.alertStatusRecordPr1.isEmpty() && viewModel.alertStatusRecordBp1.isEmpty() && FileUtils.isFirstLineEndsWith(alarmRecord1,"开始")){
                                Log.e("zsy","异常信息结束")
                                alarmRecord1="${viewModel.monitorCode1}:异常状态:${viewModel.sdfWarning.format(Date())}:结束\n${alarmRecord1}"
                                binding.layoutMonitorInterface2.tvEarlyWarningRecord.text="${alarmRecord1}"
                                viewModel.exception("", "0", "", "")
                            }

                            viewModel.excelListData.add(
                                MonitorRecordsBean(bloodDonationCode="${viewModel.monitorCode1}",
                                name="${viewModel.monitorName1}",
                                sex="${viewModel.monitorSex1}",
                                age="${viewModel.monitorAge1}",
                                bloodOxygen="${spo}",
                                bloodPressure="${viewModel.bpData1}",
                                pulse="${pr}",
                                temperature="${viewModel.temperature}",
                                monitorTime="${viewModel.sdfEarlyWarning.format(Date())}",
                                earlyWarningTime="${earlyWarningTime}",
                                reasonsEarlyWarning="${viewModel.alertStatusRecordSpo1}${viewModel.alertStatusRecordPr1}${viewModel.alertStatusRecordBp1}",
                                dataAcquisitionDeviceNumber="")
                            )
                            viewModel.bpData1=""
                            viewModel.temperature=""
                            Log.e("zsy","数据个数=${viewModel.excelListData.size}")
                            if (viewModel.excelListData.size>=50){
                                viewModel.excelListDataTemp.addAll(viewModel.excelListData)
                                lifecycleScope.launch(Dispatchers.IO){
                                    viewModel.excelListData.clear()
                                    Log.e("zsy","现在这里有几个数据${viewModel.excelListDataTemp.size}")
                                    val result = excelService.bloodCollectExportExcel1(viewModel.excelListDataTemp, viewModel.headList, viewModel.filePath)
                                    delay(2000)
                                    withContext(Dispatchers.Main){
                                        if (result) {
                                            // 可以在这里添加一些提示信息，比如Toast提示导出成功等
                                            Log.e("zsy","数据已成功导出到Excel文件")
                                            viewModel.excelListDataTemp.clear()
                                        } else {
                                            // 同样可以添加提示信息告知导出失败
                                            Log.e("zsy","数据导出失败，请检查相关设置")
                                        }
                                    }
                                }
                            }
                        }else{
                            binding.tvMonitoringControl1.text="开始监测"
                        }
                    }
                }
                3->{
                    binding.layoutMonitorInterface2.tvSpoConnectStatus.text="已连接 ${O2RingName}"
                    loadProgressDialog.dismiss()
                    viewModel.o2ringConnectStatus1=1
                    handler.postDelayed(spo,2000)
                }
                4->{
                    if (it.bleData!!.contains("血氧")){
                        viewModel.o2ringConnectStatus1=0
                    }
                    binding.layoutMonitorInterface2.tvSpoConnectStatus.text="未连接 ${O2RingName}"
                    loadProgressDialog.dismiss()

                }
                5->{
                    binding.layoutMonitorInterface1.tvBpConnectStatus.text="已连接 ${BPName}"
                    loadProgressDialog.dismiss()
                    handler.postDelayed(bp,10000)
                    viewModel.bPConnectStatus1=true
                    LiveEventBus.get("receiveCmd2",SendCmd::class.java).postDelay(SendCmd(type = 1, cmd = BPStartCmd),500)
                    binding.layoutMonitorInterface1.tvStartBp.text="停止测量"
                }
                6->{
                    binding.layoutMonitorInterface1.tvBpConnectStatus.text="未连接 ${BPName}"
                    loadProgressDialog.dismiss()
                    viewModel.bPConnectStatus1=false
                    ToastUtils.show(it.bleData)
                    binding.layoutMonitorInterface1.tvStartBp.text="开始测量"
                }
                7->{
                    var temp=viewModel.hexStringToFloat(it.bleData!!)
                    Log.e("zsy","${it.bleData}  转换后=${temp}")
                    temp= (kotlin.math.round(temp * 10) / 10f).toFloat()
                    Log.e("zsy","temp转换后=${temp}")
                    viewModel.temperature=temp.toString()
                    addData1(temp)
                }
                8->{
                    binding.layoutMonitorInterface1.tvTemperaConnectStatus.text="已连接 ${TempName}"
                    loadProgressDialog.dismiss()
                    viewModel.tempConnectStatus1=true
                    LiveEventBus.get("receiveCmd2",SendCmd::class.java).postDelay(SendCmd(type = 1, cmd = tempStartCmd),2000)
                }
                9->{
                    binding.layoutMonitorInterface1.tvTemperaConnectStatus.text="未连接 ${TempName}"
                    temperatureConnectConnect=0
                    viewModel.tempConnectStatus1=false
                }
            }
        })

        viewModel.dataMsg.observe(this, androidx.lifecycle.Observer {
            loadProgressDialog.dismiss()
            if (it=="1"){
                lifecycleScope.launch(Dispatchers.IO) {
                    Log.e("zsy","${viewModel.monitorCode1}")
                    viewModel.insertRecord(
                        MonitorRecordEntity(bloodDonationCode=viewModel.monitorCode1,
                            name=viewModel.monitorName1,sex=viewModel.monitorSex1,
                            warningTimes=viewModel.numberEarlyWarning1,dateStr=viewModel.sdfFile.format(Date()),
                            fileAddress=viewModel.filePath)
                    )
                    withContext(Dispatchers.Main){
                        viewModel.excelId=""
                        viewModel.filePath=""
                        viewModel.monitorCode1=""
                        viewModel.monitorName1=""
                        viewModel.monitorSex1=""
                        viewModel.monitorAge1=""
                        viewModel.numberEarlyWarning1=0
                        binding.layoutMonitorInterface1.scanCodeLayout.visibility= View.VISIBLE
                        binding.layoutMonitorInterface1.bloodDonationInfoLayout.visibility= View.GONE
                        binding.layoutMonitorInterface1.tvScanCodeNum.text=""
                        binding.layoutMonitorInterface1.tvPersonInfo.text="个人信息"
                        viewModel.bpList1.clear()
                        adapter1.notifyDataSetChanged()
                    }
                }
            }else{
                if (it.contains("上传失败")){
                    Toast.makeText(requireContext(),"${it}",Toast.LENGTH_LONG).show()
                }
            }
        })
    }



    fun initChart1() {
        // 启用触摸和拖动
        binding.layoutMonitorInterface1.lineChart1.setTouchEnabled(false)
        binding.layoutMonitorInterface1.lineChart1.setDragEnabled(false)
        binding.layoutMonitorInterface1.lineChart1.setScaleEnabled(false)
        binding.layoutMonitorInterface1.lineChart1.setNoDataText("暂无数据")
        // 图例设置
        val legend: Legend = binding.layoutMonitorInterface1.lineChart1.getLegend()
        legend.isEnabled = false
        legend.form = Legend.LegendForm.LINE
        legend.textColor = Color.BLACK
        // X轴设置
        val xAxis: XAxis = binding.layoutMonitorInterface1.lineChart1.getXAxis()
        xAxis.position = XAxis.XAxisPosition.BOTTOM
        xAxis.textColor = Color.BLACK
        // 设置X轴的最小和最大值以匹配数据点
        xAxis.axisMaximum = (maxVisibleDataPoints - 1).toFloat()
        xAxis.axisMinimum = 0f
        xAxis.setDrawGridLines(false)
        xAxis.granularity = 1f // 设置粒度为1，确保标签逐个显示
        xAxis.setLabelCount(maxVisibleDataPoints, true) // 设置X轴标签数量，与可见数据点数相同
        xAxis.setDrawAxisLine(true) // 保留X轴的轴线（顶部的那条线是X轴的轴线）
        xAxis.valueFormatter = object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                val index = value.toInt()
                return if (index >= 0 && index < viewModel.timeStamps1.size) {
                    viewModel.timeStamps1[index]
                } else ""
            }
        }
        xAxis.textSize = 6f
        // 左侧Y轴设置（体温）
        val leftAxis: YAxis = binding.layoutMonitorInterface1.lineChart1.axisLeft
        leftAxis.axisMaximum = 45f // 温度最大值
        leftAxis.axisMinimum = 15f // 温度最小值
        leftAxis.granularity = 3f // 温度刻度间隔
        leftAxis.textColor = Color.BLACK
        leftAxis.textSize=8.0f
        leftAxis.setDrawGridLines(true) // 显示左侧的网格线
        leftAxis.setDrawAxisLine(true) // 保留左侧的轴线（实线）
        leftAxis.enableGridDashedLine(10f, 10f, 0f) // 使用 DashPathEffect 实现虚线效果
        leftAxis.valueFormatter = viewModel.TemperatureFormatter()
        val rightAxis: YAxis = binding.layoutMonitorInterface1.lineChart1.axisRight
//        rightAxis.isEnabled = false // 直接禁用右侧Y轴，这样通常会隐藏其所有相关元素
        // 或者分别设置各元素的显示属性，如下：
        rightAxis.setDrawAxisLine(true) // 隐藏轴线
        rightAxis.setDrawGridLines(false) // 隐藏网格线
        rightAxis.setDrawLabels(false) // 隐藏刻度标签值
        rightAxis.valueFormatter = viewModel.TemperatureRightFormatter()
        // 隐藏描述标签
        binding.layoutMonitorInterface1.lineChart1.description.isEnabled = false
    }

    fun initChart2() {
        // 启用触摸和拖动
        binding.layoutMonitorInterface2.lineChart1.setTouchEnabled(false)
        binding.layoutMonitorInterface2.lineChart1.setDragEnabled(false)
        binding.layoutMonitorInterface2.lineChart1.setScaleEnabled(false)
        binding.layoutMonitorInterface2.lineChart1.setNoDataText("暂无数据")
        // 图例设置
        val legend: Legend = binding.layoutMonitorInterface2.lineChart1.getLegend()
        legend.isEnabled = false
        legend.form = Legend.LegendForm.LINE
        legend.textColor = Color.BLACK
        // X轴设置
        val xAxis: XAxis = binding.layoutMonitorInterface2.lineChart1.getXAxis()
        xAxis.position = XAxis.XAxisPosition.BOTTOM
        xAxis.textColor = Color.BLACK
        // 设置X轴的最小和最大值以匹配数据点
        xAxis.axisMaximum = (maxVisibleDataPoints - 1).toFloat()
        xAxis.axisMinimum = 0f
        xAxis.setDrawGridLines(false)
        xAxis.granularity = 1f // 设置粒度为1，确保标签逐个显示
        xAxis.setLabelCount(maxVisibleDataPoints, true) // 设置X轴标签数量，与可见数据点数相同
        xAxis.setDrawAxisLine(true) // 保留X轴的轴线（顶部的那条线是X轴的轴线）
        xAxis.valueFormatter = object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                val index = value.toInt()
                return if (index >= 0 && index < viewModel.timeStamps2.size) {
                    viewModel.timeStamps2[index]
                } else ""
            }
        }
        xAxis.textSize = 6f
        // 左侧Y轴设置（血氧）
        val leftAxis: YAxis = binding.layoutMonitorInterface2.lineChart1.axisLeft
        leftAxis.axisMaximum = 100f // 血氧最大值
        leftAxis.axisMinimum = 85f // 血氧最小值
        leftAxis.granularity = 5f // 血氧刻度间隔
        leftAxis.textColor = Color.BLACK
        leftAxis.textSize=8.0f
        leftAxis.setDrawGridLines(false) // 显示左侧的网格线
        leftAxis.setDrawAxisLine(true) // 保留左侧的轴线（实线）
        leftAxis.enableGridDashedLine(10f, 10f, 0f) // 使用 DashPathEffect 实现虚线效果
        // 自定义电压刻度格式
        leftAxis.valueFormatter = viewModel.OxygenFormatter()
        // 右侧Y轴设置（脉搏）
        val rightAxis: YAxis = binding.layoutMonitorInterface2.lineChart1.axisRight
        rightAxis.axisMaximum = 210f // 脉搏最大值
        rightAxis.axisMinimum = 30f // 脉搏最小值
        rightAxis.granularity = 30f // 脉搏刻度间隔
        rightAxis.textColor = Color.BLACK
        rightAxis.textSize=8.0f
        rightAxis.setDrawGridLines(true) // 显示右侧的网格线
        rightAxis.setDrawAxisLine(true) // 保留右侧的轴线（实线）
        rightAxis.enableGridDashedLine(5f, 5f, 0f) // 使用 DashPathEffect 实现虚线效果
        // 自定义电流刻度格式
        rightAxis.valueFormatter = viewModel.HeartFormatter()
        // 隐藏描述标签
        binding.layoutMonitorInterface2.lineChart1.description.isEnabled = false
    }

    // 添加数据的方法
    fun addData1(temperature: Float) {
        val currentTimeMillis = System.currentTimeMillis()
        val date = Date(currentTimeMillis)
        if (viewModel.temperatureData.size >= maxVisibleDataPoints) {
            viewModel.temperatureData.removeAt(0)
            viewModel.timeStamps1.removeAt(0)
            // 调整剩余数据的X轴位置
            for (i in viewModel.temperatureData.indices) {
                viewModel.temperatureData[i].x = i.toFloat()
            }
        }
        // 添加新数据点
        viewModel.temperatureData.add(Entry(viewModel.temperatureData.size.toFloat(), temperature.toFloat()))
        viewModel.timeStamps1.add(dateFormat.format(date))
        // 更新图表数据
        val temperatureDataSet = createOxygenLineDataSet1(viewModel.temperatureData, "温度℃", Color.parseColor("#DFB81D"))
        val lineData = LineData(temperatureDataSet)
        binding.layoutMonitorInterface1.lineChart1.data = lineData
        binding.layoutMonitorInterface1.lineChart1.invalidate() // 刷新图表
    }

    // 添加数据的方法
    fun addData2(oxygen: Int, pulse: Int) {
        val currentTimeMillis = System.currentTimeMillis()
        val date = Date(currentTimeMillis)
        if (viewModel.oxygenData.size >= maxVisibleDataPoints) {
            viewModel.oxygenData.removeAt(0)
            viewModel.pulseData.removeAt(0)
            viewModel.timeStamps2.removeAt(0)
            // 调整剩余数据的X轴位置
            for (i in viewModel.oxygenData.indices) {
                viewModel.oxygenData[i].x = i.toFloat()
                viewModel.pulseData[i].x = i.toFloat()
            }
        }
        // 添加新数据点
        viewModel.oxygenData.add(Entry(viewModel.oxygenData.size.toFloat(), oxygen.toFloat()))
        viewModel.pulseData.add(Entry(viewModel.pulseData.size.toFloat(), pulse.toFloat()))
        viewModel.timeStamps2.add(dateFormat.format(date))
        // 更新图表数据
        val oxygenDataSet = createOxygenLineDataSet2(viewModel.oxygenData, "血氧(%)", Color.parseColor("#F82C2C"))
        val heartDataSet = createPulseLineDataSet2(viewModel.pulseData, "脉搏(次/分)", Color.parseColor("#0BAB10"))
        heartDataSet.axisDependency = YAxis.AxisDependency.RIGHT
        val lineData = LineData(oxygenDataSet, heartDataSet)
        binding.layoutMonitorInterface2.lineChart1.data = lineData
        binding.layoutMonitorInterface2.lineChart1.invalidate() // 刷新图表
    }

    // 创建数据集的方法
    fun createOxygenLineDataSet1(data: List<Entry>, label: String, color: Int): LineDataSet {
        val lineDataSet = LineDataSet(data, label)
        lineDataSet.color = color
        lineDataSet.lineWidth = 1f
        lineDataSet.setDrawCircles(false)
        lineDataSet.setDrawValues(false)
        lineDataSet.mode= LineDataSet.Mode.CUBIC_BEZIER
        lineDataSet.cubicIntensity = 0.2f
        lineDataSet.setDrawFilled(true)
        lineDataSet.fillFormatter = IFillFormatter { _, _ ->
            binding.layoutMonitorInterface1.lineChart1.axisLeft.axisMinimum
        }
        var drawable = ContextCompat.getDrawable(requireContext(), R.drawable.temperature_fade_red)
        drawable?.alpha = 100
        lineDataSet.fillDrawable = drawable
        return lineDataSet
    }



    // 创建数据集的方法
    fun createOxygenLineDataSet2(data: List<Entry>, label: String, color: Int): LineDataSet {
        val lineDataSet = LineDataSet(data, label)
        lineDataSet.color = color
        lineDataSet.lineWidth = 1f
        lineDataSet.setDrawCircles(false)
        lineDataSet.setDrawValues(false)
        lineDataSet.mode= LineDataSet.Mode.CUBIC_BEZIER
        lineDataSet.cubicIntensity = 0.2f
        lineDataSet.setDrawFilled(true)
        lineDataSet.fillFormatter = IFillFormatter { _, _ ->
            binding.layoutMonitorInterface2.lineChart1.axisLeft.axisMinimum
        }
        var drawable = ContextCompat.getDrawable(requireContext(), R.drawable.oxygen_fade_red)
        drawable?.alpha = 100
        lineDataSet.fillDrawable = drawable
        return lineDataSet
    }

    // 创建数据集的方法
    fun createPulseLineDataSet2(data: List<Entry>, label: String, color: Int): LineDataSet {
        val lineDataSet = LineDataSet(data, label)
        lineDataSet.color = color
        lineDataSet.lineWidth = 1f
        lineDataSet.setDrawCircles(false)
        lineDataSet.setDrawValues(false)
        lineDataSet.mode= LineDataSet.Mode.CUBIC_BEZIER
        lineDataSet.cubicIntensity = 0.2f
        lineDataSet.setDrawFilled(true)
        lineDataSet.fillFormatter = IFillFormatter { _, _ ->
            binding.layoutMonitorInterface2.lineChart1.axisRight.axisMinimum
        }
        var drawable = ContextCompat.getDrawable(requireContext(), R.drawable.pulse_fade_red)
        drawable?.alpha = 100
        lineDataSet.fillDrawable = drawable
        return lineDataSet
    }

    fun  infoFillIn(){
        DialogUtil.showCustomDialogWithCountdown(
            requireActivity(),
            DialogUtil.DialogType.INFO,
            onPositiveButtonClick = {param1, param2, param3 ->
                // 确定按钮点击事件的逻辑
                viewModel.monitorName1=param1
                viewModel.monitorAge1=param2
                viewModel.monitorSex1=if (param3=="1") "男" else "女"
                binding.layoutMonitorInterface1.tvPersonInfo.text="姓名:${param1} \n\n年龄:${param2}  性别:${viewModel.monitorSex1}"
            },
            onNegativeButtonClick = {
                // 取消按钮点击事件的逻辑
            }
        )
    }

    val REQUEST_CODE_SCAN = 1002

    fun startScan() {
        val intent = Intent(requireActivity(), CaptureActivity::class.java)
        startActivityForResult(intent, REQUEST_CODE_SCAN)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_SCAN && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                var result=data.extras!!["SCAN_RESULT"].toString()
                Log.e("zsy","${result}")
                if (result.isNotEmpty()){
                  if (result.isNotEmpty()) {
                      viewModel.monitorCode1=result
                      binding.layoutMonitorInterface1.scanCodeLayout.visibility = View.GONE
                      binding.layoutMonitorInterface1.bloodDonationInfoLayout.visibility = View.VISIBLE
                      binding.layoutMonitorInterface1.scanCodeImg.setImageBitmap(result.encodeAsBitmap(750, 140))
                      binding.layoutMonitorInterface1.tvScanCodeNum.text = "$result"
                      infoFillIn()
                  }
                }
                /*  for (key in keys) {
                      Log.e("zsy", "Key: " + key + ", Value: " + data.extras!![key])
                      if (key.equals("SCAN_RESULT")){
                          var result=data.extras!![key].toString()
                      }
                  }*/
            }
        }
    }



}